package com.twp.auth.repository.auth;

import com.twp.auth.domain.authority.RequestUrl;
import com.twp.auth.domain.authority.Role;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

@Repository
public interface RequestUrlRepository extends JpaRepository<RequestUrl, Integer>, JpaSpecificationExecutor<RequestUrl> {

    RequestUrl findByUrlAndMethod(String url, String method);

    RequestUrl findAllByCode(String code);

    @Query(nativeQuery = true,value = "SELECT * FROM twp_request_url ")
    List<RequestUrl> findByMenuCode();

    List<RequestUrl> findAllByIdIn(List<Integer> ids);


    @Query(nativeQuery = true,
            value = "SELECT requestUrl.* FROM twp_request_url requestUrl\n" +
            "    WHERE NOT exists(\n" +
            "        SELECT * FROM twp_menu menu INNER JOIN twp_menu_requestUrl menuRequest ON menu.id = menuRequest.menuId\n" +
            "            INNER JOIN twp_request_url requestUrl1 ON requestUrl1.id = menuRequest.requestUrlId\n" +
            "        WHERE requestUrl.id = requestUrl1.id AND menu.code = :menuCode \n" +
            "    ) \n#pageable\n")
    Page<RequestUrl> findForNeedBindRequest(@Param(value = "menuCode") String menuCode, Pageable pageable);

    /*
    取消绑定
     */
    @Modifying
    @Query(
            nativeQuery = true,
            value = "DELETE menuRequest FROM twp_menu_requestUrl menuRequest " +
                    "INNER JOIN twp_menu menu ON menuRequest.menuId = menu.id " +
                    "WHERE menu.code = :menuCode AND menuRequest.requestUrlId in :requestMappingIds "
    )
    void cancelBind(@Param(value = "menuCode")String menuCode,@Param(value = "requestMappingIds")List<Integer> requestMappingIds);
}


